<?php
namespace app\index\controller;

use think\Request;
use app\common\enums\ResultEnum;
use app\common\model\Admin as AdminModel;
use app\common\utils\ResultVOUtil;
use think\facade\Log;
use app\common\model\Role;
use app\common\model\Agency;
use app\common\service\Access;
use app\common\model\AdminAgency;
use app\common\model\AdminRole;

class Admin extends Base
{

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request, $page = 1, $length = 10)
    {
        $data = $request->post();
        $agency_id = session('admin.agency_id');
        $where = [];
        if (strpos($agency_id, '1') === false) {
            $admin = AdminAgency::where('agency_id', 'in', $agency_id)->column('admin_id');
            $admin_id = implode(',', array_unique($admin));
            $where[] = [
                'id',
                'in',
                $admin_id
            ];
        }

        if (! empty($data['search'])) {
            $where[] = [
                'nick_name|user_name',
                'like',
                '%' . $data['search'] . '%'
            ];
        }

        try {
            $model = AdminModel::with('agency,role')->where($where)->paginate($length, false, [
                'type' => 'bootstrap',
                'var_page' => 'page',
                'page' => $page
            ]);
        } catch (\Exception $e) {
            Log::record('用户表查询数据:' . $e->getMessage(), 'error');
            return ResultVOUtil::error(ResultEnum::ERROR);
        }

        return ResultVOUtil::success($model);
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $data = [];
        $agency_id = session('admin.agency_id');
        
        if (strpos($agency_id, '1') === false) {
            $data['agency'] = Agency::where('id', 'in', $agency_id)->select();
            $data['role'] = Role::where('agency_id', 'in', '1,'.$agency_id)->select(); 
        } else {
            $data['agency'] = Agency::all();
            $data['role'] = Role::all();
        }
        return ResultVOUtil::success($data);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->param();
        if (! empty($data)) {

            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            $agency_id = session('admin.agency_id');
            
            if (strpos($agency_id, '1') === false) {
                $agency = explode(',', $agency_id);
                $data_diff = array_diff($data['agency_id'], $agency);
            } else{
                $data_diff = [];
            }

            if (! empty($data_diff)) {
                return ResultVOUtil::error(ResultEnum::ERROR['code'], '权限不足');
            } else {
                $model = new AdminModel();
                $model->startTrans();
                try {
                    $model->allowField(true)->save($data);
                } catch (\Exception $e) {
                    $model->rollback();
                    Log::record('[新增用戶]:' . $e->getMessage(), 'error');
                    return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
                }
                if ($model->id) {
                    $roleData = Access::roleData($data['role_id'], $model->id);
                    $agencyData = Access::agencyData($data['agency_id'], $model->id);
                    $adminAgency = new AdminAgency();
                    $adminRole = new AdminRole();

                    try {
                        $adminRole->insertAll($roleData);
                        $adminAgency->insertAll($agencyData);
                    } catch (\Exception $e) {
                        $model->rollback();
                        Log::record('[新增用戶]:' . $e->getMessage(), 'error');
                        return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
                    }
                    $model->commit();
                    return ResultVOUtil::success('添加成功');
                }
            }
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $data = [];

        try {

           $admin = AdminModel::where(['id' => $id])->field('id,nick_name,user_name,email,notes')->find();
            $data['admin'] = $admin; 
        } catch (\Exception $e) {

            Log::record('[admin表查询数据]:' . $e->getMessage(), 'error');
            return ResultVOUtil::error(ResultEnum::FIND_ERROR);
        }

        try {
            $data['admin']['agency_id'] = AdminAgency::where(['admin_id'=>$id])->column('agency_id');
             
            $agency_id = session('admin.agency_id');
            if (strpos($agency_id, '1') === false) {
                $data['agency'] = Agency::where('id', 'in', $agency_id)->select();
                $data['role'] = Role::where('agency_id', 'in', '1,'.$agency_id)->select(); 
            } else {
                $data['agency'] = Agency::all();
                $data['role'] = Role::all();
            } 
      
        } catch (\Exception $e) {

            Log::record('[agency表查询数据]:' . $e->getMessage(), 'error');
            return ResultVOUtil::error(ResultEnum::FIND_ERROR);
        }

        try {

            $role = AdminRole::where(['admin_id' => $id])->column('role_id');
            $data['admin']['role_id'] = $role;

        } catch (\Exception $e) {

            Log::record('[role表查询数据]:' . $e->getMessage(), 'error');
            return ResultVOUtil::error(ResultEnum::FIND_ERROR);
        }

        return ResultVOUtil::success($data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $data = $request->param();
        if (! empty($data)) {
        
            $agency_id = session('admin.agency_id');
            
            if (strpos($agency_id, '1') === false) {
                $agency = explode(',', $agency_id);
                $data_diff = array_diff($data['agency_id'], $agency);
            } else{
                $data_diff = [];
            }
            
            if (! empty($data_diff)) {
                return ResultVOUtil::error(ResultEnum::ERROR['code'], '权限不足');
            } else {
                $model = new AdminModel();
                $model->startTrans();
                try {
                    $model->allowField(true)->isUpdate(true) ->save($data);
                } catch (\Exception $e) {
                    $model->rollback();
                    Log::record('[admin表更新数据]:' . $e->getMessage(), 'error');
                    return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
                }
                if ($model->id) {
                    AdminAgency::where([ 'admin_id' => $model->id])->delete();
                    AdminRole::where(['admin_id' => $model->id])->delete();
                    $roleData = Access::roleData($data['role_id'], $model->id);
                    $agencyData = Access::agencyData($data['agency_id'], $model->id);
                    $adminAgency = new AdminAgency();
                    $adminRole = new AdminRole();
                    
                    try {
                        $adminRole->insertAll($roleData);
                        $adminAgency->insertAll($agencyData);
                    } catch (\Exception $e) {
                        $model->rollback();
                        Log::record('[用戶加盟商角色表插入數據]:' . $e->getMessage(), 'error');
                        return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
                    }
                    $model->commit();
                    return ResultVOUtil::success('更新成功');
                }
            }
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
